package com.taobao.wolfwolf.web.servler;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.tree.DefaultElement;
import org.springframework.context.ApplicationContext;

import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.LogisticsOfflineSendRequest;
import com.taobao.api.request.LogisticsOnlineSendRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.wolfwolf.hibernate.pojo.Express;
import com.taobao.wolfwolf.hibernate.pojo.ReceiverAddress1;
import com.taobao.wolfwolf.hibernate.service.ExpressService;
import com.taobao.wolfwolf.taobao.ExpressCollect;
import com.taobao.wolfwolf.taobao.PrintKd;
import com.taobao.wolfwolf.taobao.TaoBaoUtil;
import com.taobao.wolfwolf.util.ReadIni;


public class PrintExpress extends HttpServlet {

	private static final long serialVersionUID = 213556692791426596L;
	private static Logger logger = Logger.getLogger(PrintExpress.class);
	
	private static int ONLINE_SEND = 1;
	
	private TaobaoClient client;
	private ReceiverAddress1 radd;

	public PrintExpress() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	
	/**
	 * <p>设置快递单中的字段</p>
	 * @param tid
	 */
	private String setRadd(long tid) {
		radd = new ReceiverAddress1();
		
		TradeFullinfoGetRequest req=new TradeFullinfoGetRequest();
		req.setFields("buyer_nick,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_phone,receiver_mobile");
		req.setTid(tid);
		
		try {
			String resutl = "";
			TradeFullinfoGetResponse r = client.execute(req , TaoBaoUtil.SESSIONKEY);
			
			Document document = DocumentHelper.parseText(r.getBody());

			@SuppressWarnings("unchecked")
			List<DefaultElement> list = document.selectNodes("//trade_fullinfo_get_response/trade");

			for (DefaultElement element : list) {
				
				// 买家 id
				String buyer_nick = element.elementText("buyer_nick");
				radd.setBuyer_nick(buyer_nick);
				
				// 收件人名称
				String receiver_name = element.elementText("receiver_name");
				radd.setReceiver_name(receiver_name);
				
				// 省
				String receiver_state = element.elementText("receiver_state");
				if(receiver_state != null)
					radd.setReceiver_txt_state(receiver_state);
				
				// 市
				String receiver_city = element.elementText("receiver_city");
				if(receiver_city != null)
					radd.setReceiver_txt_city(receiver_city);
				
				// 区
				String receiver_district = element.elementText("receiver_district");
				if(receiver_district != null)
					radd.setReceiver_txt_district(receiver_district);
				
				// 街道
				String receiver_address = element.elementText("receiver_address");
				if(receiver_address != null)
					radd.setReceiver_street(receiver_address);
				
				// 手机
				String receiver_mobile = element.elementText("receiver_mobile");
				if(receiver_mobile != null)
					radd.setReceiver_mobile(receiver_mobile);
				
				// 固定电话
				String receiver_phone = element.elementText("receiver_phone");
				if(receiver_phone != null) 
					radd.setReceiver_phone(receiver_phone);
				
				return resutl +  receiver_state + receiver_city + receiver_district + receiver_address + "\n";
			}
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	/**
	 * <p>淘宝发货</p>
	 * @param tid
	 * 		订单号
	 * @param outSid
	 * 		运单号
	 * @param companyCode
	 * 		快递公司代码
	 * @param onlineOroffline
	 * 		是否在线下单
	 */
	private void sendGoods(long tid, String outSid, String companyCode, int onlineOroffline) {
		if(ONLINE_SEND == onlineOroffline) {
			LogisticsOnlineSendRequest req=new LogisticsOnlineSendRequest();
			req.setTid(tid);
			req.setOutSid(outSid);
			req.setCompanyCode(companyCode);
			
			try {
				client.execute(req , TaoBaoUtil.SESSIONKEY);
			} catch (ApiException e) {
				logger.error(e);
				e.printStackTrace();
			}
		} else {
			LogisticsOfflineSendRequest req=new LogisticsOfflineSendRequest();
			req.setTid(tid);
			req.setOutSid(outSid);
			req.setCompanyCode(companyCode);
			
			try {
				client.execute(req , TaoBaoUtil.SESSIONKEY);
			} catch (ApiException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("utf8");
		
		ApplicationContext context = org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		ExpressService eservice = (ExpressService) context.getBean("ExpressService");
		
		PrintWriter out = response.getWriter();
		
		String tids = request.getParameter("tid");
		String express_name = request.getParameter("express");
		String serial = request.getParameter("serial");
		
		boolean send_goods_flag = Boolean.valueOf(request.getParameter("send_goods_flag"));
		boolean print_flag = Boolean.valueOf(request.getParameter("print_flag"));
		
		String path = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\";
		
		ReadIni readAwbIni = new ReadIni(path + "awb.ini");
		ReadIni readSerialCodeIni = new ReadIni(path + "serialcode.ini");
		
		if(serial == null) {
			serial = readSerialCodeIni.getProperty("express_count");
		}
		
		if(express_name == null)
			express_name = "STO";
		
		// 按快递代码获取快递类
		Express express = eservice.findExpressByCode(express_name);
		
		int express_count = Integer.valueOf(serial);
		
		express.setCount(express_count);
		
		out.println("<html>");
		out.println("<head>");
		out.println("<script type=\"text/javascript\" src=\"../js/jquery-latest.js\"></script>");
		out.println("<script type=\"text/javascript\" src=\"../js/comm.js\"></script>");
		out.println("</head>");
		out.println("<body onload=\"bindKeyCloseWin();\">");
		out.println("<table align=\"center\">");
		out.println("<tr>");
		
		// 如果只是发货
		if(send_goods_flag) {
			String awb = request.getParameter("awb");
			int online_send = Integer.valueOf(request.getParameter("online_send"));
			
			// 遍历合并的订单,一起发货
			for(String tid : tids.split(",")) {
				// TODO 当有多个订单合并成一个订单,且又使用线上下单方式发快速,就会有问题(问题是,会下多个订单,但实际上是只有一个订单)
				long t = Long.valueOf(tid);
				sendGoods(t, awb, express.getCodeName(), online_send);
			}
			String p = express.getCodeName().toLowerCase() + ".awb";
			
			// 更新运单号
			readAwbIni.saveProperty(p, Long.valueOf(awb) + 1);
			out.println("<td colspan=\"2\">");
			out.println("成功发货" + tids.split(",").length + "单");
			out.println("</td>");
		}
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>");
		out.println("发件人地址:");
		out.println("</td>");
		out.println("<td>");
		out.println(setRadd(getTid(tids)));
		out.println("</td>");
		
		out.println("</tr>");
		
		// 如果只是打印
		if(print_flag) {
			new PrintKd(express, radd);
			readSerialCodeIni.saveProperty("express_count", express_count + 1);
		}
		
		out.println("</tr>");
		out.println("</table>");
		out.println("</body>");
		out.println();
		out.println("</html>");
		
		out.flush();
		out.close();
	}
	
	private long getTid(String tid) {
		return Long.valueOf(tid.split(",")[0]);
	}

	public void init() throws ServletException {
		client = new DefaultTaobaoClient(TaoBaoUtil.TAOBAO_F_URL, TaoBaoUtil.APP_KEY, TaoBaoUtil.APP_SERCET, Constants.FORMAT_XML);
	}

}
